//
//  MYGRegisterController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/2/26.
//

import UIKit
import QMUIKit
import HandyJSON

class MYGRegisterController: MYGBaseController {
    var isUserAgreementChecked = false
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
    }
    
    // MARK: - UI
    private func configUI() {
        self.title = "注册"
        view.backgroundColor = .white
//        view.addSubviews([logoImageView, phoneTextField, codeTextField, loginButton, leftLineView, orLabel, rightLineView, wechatButton, delegateButton])
        view.addSubviews([logoImageView, phoneTextField, codeTextField, loginButton,tipLabel, delegateButton])
        
        logoImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(38+navHeight+statusBarHeight)
            make.width.height.equalTo(67)
        }
        
        phoneTextField.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(32)
            make.height.equalTo(60)
            make.top.equalTo(logoImageView.snp.bottom).offset(25)
        }
        
        codeTextField.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(32)
            make.height.equalTo(60)
            make.top.equalTo(phoneTextField.snp.bottom).offset(0)
        }
        
        loginButton.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(28)
            make.top.equalTo(codeTextField.snp.bottom).offset(35)
            make.height.equalTo(39)
        }
        tipLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(loginButton.snp.bottom).offset(10)
        }
        
//        leftLineView.snp.makeConstraints { make in
//            make.left.equalToSuperview().offset(100)
//            make.right.equalTo(orLabel.snp.left).offset(-20)
//            make.centerY.equalTo(orLabel)
//            make.height.equalTo(0.5)
//        }
//        
//        orLabel.snp.makeConstraints { make in
//            make.centerX.equalToSuperview()
//            make.top.equalTo(loginButton.snp.bottom).offset(40)
//        }
//        
//        rightLineView.snp.makeConstraints { make in
//            make.right.equalToSuperview().offset(-100)
//            make.left.equalTo(orLabel.snp.right).offset(20)
//            make.centerY.equalTo(orLabel)
//            make.height.equalTo(0.5)
//        }
//        
//        wechatButton.snp.makeConstraints { make in
//            make.top.equalTo(orLabel.snp.bottom).offset(28)
//            make.centerX.equalToSuperview()
//        }
            
        delegateButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.bottom.equalToSuperview().offset(-30-bottomSafeheight)
        }
        
//        orLabel.setContentHuggingPriority(.required, for: .horizontal)
//        orLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
    }
    
    // MARK: - lazy load
    private lazy var logoImageView: UIImageView = {
        let imgV = UIImageView()
        imgV.image = UIImage(named: "Register/icon")
        return imgV
    }()
    
    private lazy var phoneTextField: MYGRegisterTextField = {
        let tf = MYGRegisterTextField()
        tf.imageView.image = UIImage(named: "Register/phone")
        tf.textField.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("请输入手机号码")?.font(.regular(16)).textColor(.rgba(221, 221, 221, 1))
        })
        tf.sendButton.isHidden = true
//        #if DEBUG
//        tf.textField.text = "13899138554" //"18280265560" 16601105106 13899138669 13888138888 13888888888 13899138993   13899138554
//        #endif
//        tf.textField.text = "16601105106"
        return tf
    }()
    
    private lazy var codeTextField: MYGRegisterTextField = { 
        let tf = MYGRegisterTextField()
        tf.imageView.image = UIImage(named: "Register/code")
        tf.textField.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("请输入验证码")?.font(.regular(16)).textColor(.rgba(221, 221, 221, 1))
        })
        tf.sendAction = {[weak self] in
            self?.sendCodeRequest()
        }
       
//        tf.textField.text = "520520"
        return tf
    }()
    
    private lazy var loginButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("登录", for: .normal)
        btn.titleLabel?.font = .regular(16)
        btn.setTitleColor(.white, for: .normal)
        //btn.backgroundColor = .rgba(162, 146, 254, 1)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.addTarget(self, action: #selector(login), for: .touchUpInside)
        btn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                 UIColor.init(hexString: "#4975EC").cgColor],
                                        startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))

        return btn
    }()
    
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(12)
        label.textColor = .rgba(102, 102, 102, 1)
        label.text = "登录后自动注册成为会员"
        label.textAlignment = .center
        return label
    }()
    
    
    
    private lazy var leftLineView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(151, 151, 151, 0.26)
        return view
    }()
    
    private lazy var orLabel: UILabel = {
        let label = UILabel()
        label.font = .regular(16)
        label.textColor = .rgba(221, 221, 221, 1)
        label.text = "或"
        return label
    }()
    
    private lazy var rightLineView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(151, 151, 151, 0.26)
        return view
    }()
    
    private lazy var wechatButton: QMUIButton = {
        let btn = QMUIButton()
        btn.setImage(UIImage(named: "Register/wechat"), for: .normal)
        btn.setTitle("微信授权登录", for: .normal)
        btn.spacingBetweenImageAndTitle = 11
        btn.titleLabel?.font = .regular(14)
        btn.setTitleColor(.rgba(192, 192, 192, 1), for: .normal)
        btn.imagePosition = .top
        return btn
    }()
    
    private lazy var delegateButton: QMUIButton = {
        let btn = QMUIButton()
        btn.setImage(UIImage(named: "Register/delegate"), for: .normal)
        btn.setImage(UIImage(named: "Register/delegate_sel"), for: .selected)
        btn.spacingBetweenImageAndTitle = 4
        btn.imagePosition = .left
        btn.setAttributedTitle(NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.text("登录即代表同意")?.font(.regular(14)).textColor(.rgba(102, 102, 102, 1)).tapActionByLable("agree")
            confer.text("《用户协议》")?.font(.regular(14)).textColor(.rgba(69, 131, 250, 1)).tapActionByLable("delegate")
            confer.text("《隐私协议》")?.font(.regular(14)).textColor(.rgba(69, 131, 250, 1)).tapActionByLable("yingsi")
        }), for: .normal)
        btn.titleLabel?.isUserInteractionEnabled = true
        btn.titleLabel?.rz.tapAction { label, tapActionId, range in
            print("\(tapActionId)")
            if tapActionId == "delegate" {
                let vc = MYGProtocolController(titeleName: "用户协议")
                vc.urlString = protoclUrl
                self.navigationController?.pushViewController(vc)
            }else if tapActionId == "yingsi" {
                let vc = MYGProtocolController(titeleName: "隐私协议")
                vc.urlString = privacyUrl
                self.navigationController?.pushViewController(vc)
            }
           
        }
        btn.addTarget(self, action: #selector(clickArgeeBtn(_:)), for: .touchUpInside)

        return btn
    }()
}

extension MYGRegisterController {
    
    @objc
    private func clickArgeeBtn(_ sender: QMUIButton) {
        sender.isSelected = !sender.isSelected
        self.isUserAgreementChecked = !self.isUserAgreementChecked
    }
    
    private func sendCodeRequest() {
        MYGLoading.show()
        MYGNetwork<MYGRegisterAPI, MYGEmptyModel>.request(target: MYGRegisterAPI.getCode(phone: phoneTextField.textField.text ?? "")) { _ in
            MYGLoading.hide()
            MMYGHUD.showToast(text: "短信已发送，请注意查收")
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc
    private func login() {
        
        var phone = phoneTextField.textField.text ?? ""
        phone = phone.replacingOccurrences(of: " ", with: "")
        guard phone.count > 0 else {
            MMYGHUD.showToast(text: "请输入手机号")
            return
        }
        
        guard phone.count == 11 else {
            MMYGHUD.showToast(text: "请输入11位手机号")
            return
        }
        
        guard (codeTextField.textField.text ?? "").count > 0 else {
            MMYGHUD.showToast(text: "请输入验证码")
            return
        }
        
        guard isUserAgreementChecked else {
            MMYGHUD.showToast(text: "请先勾选同意《用户协议》")
            return
        }
        
        MYGLoading.show()
        MYGNetwork<MYGRegisterAPI, MYGUserModel>.request(target: .login(phone: phoneTextField.textField.text ?? "", code: codeTextField.textField.text ?? "")) { model in
            MYGLoading.hide()
            MYGUserManager.user = model
//            if !model.doctor.name.isEmpty {
                UIViewController.keyWindow?.rootViewController = MYGTabBarController()
//            }else {
//                let vc = MYGBaseInfoController()
//                vc.model = model
//                self.navigationController?.pushViewController(vc)
//            }
            MYGSocketManager.shared.connect()
            let isSuc = MYGUserManager.isDoctorInfComplete
            MYGUserManager.isDoctorInfComplete = isSuc
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
}

class MYGRegisterTextField: UIView {
    var timer: Timer?
    var sendAction: (()->Void)?
    private var time = 60
    // MARK: - init
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        configUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    // MARK: - UI
    private func configUI() {
        backgroundColor = .white
        addSubviews([stackView, lineView])
        stackView.addArrangedSubviews([imageView, textField, sendButton])
        
        stackView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().inset(4)
            make.top.bottom.equalToSuperview()
        }
        
        lineView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        sendButton.snp.makeConstraints { make in
            make.width.equalTo(79)
            make.height.equalTo(20)
        }
        
        imageView.setContentHuggingPriority(.required, for: .horizontal)
        imageView.setContentCompressionResistancePriority(.required, for: .horizontal)
    }
    
    // MARK: - lazy load
    private lazy var stackView: UIStackView = {
        let stackV = UIStackView()
        stackV.axis = .horizontal
        stackV.spacing = 8
        stackV.alignment = .center
        return stackV
    }()
    
    fileprivate lazy var imageView: UIImageView = {
        let imgV = UIImageView()
        return imgV
    }()
    
    fileprivate lazy var textField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(16)
        tf.textColor = .black
        tf.keyboardType = .numberPad
        tf.clearButtonMode = .whileEditing
        tf.delegate = self
        return tf
    }()
    
    fileprivate lazy var sendButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("发送验证码", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .regular(13)
        btn.backgroundColor = .rgba(255, 158, 11, 1)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 10
        btn.addTarget(self, action: #selector(sendCode), for: .touchUpInside)
        return btn
    }()
    
    private lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = .rgba(151, 151, 151, 0.37)
        return view
    }()
    

}

extension MYGRegisterTextField: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        guard let stringRange = Range(range, in: currentText) else { return false }
        let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
        return updatedText.count <= 11 // 限制为11位
    }

}

extension MYGRegisterTextField {
    @objc
    private func sendCode() {
        time = 60
        sendButton.setTitle("60s", for: .disabled)
        sendButton.isEnabled = false
        
        let timer = Timer.init(timeInterval: 1, repeats: true, block: {[weak self] timer in
            guard let self = self else {
                return
            }
            time -= 1
            if time <= 0 {
                sendButton.setTitle("发送验证码", for: .normal)
                sendButton.isEnabled = true
                timer.invalidate()
                self.timer = nil
                return
            }
            
            sendButton.setTitle("\(time)s", for: .disabled)
        })
        
        self.timer = timer
        
        RunLoop.current.add(timer, forMode: .common)
        
        sendAction?()
    }
}
